package com.ruoyi.system.excelImport.pangxie.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author zyy
 * @date 2024-07-06
 */
@Slf4j
public class PangXieUtil {

    public static String getgudingzhi(String jsUrl, String str, char endChar) {
        String resStr = null;
        try {
            String body = HttpRequest.get(jsUrl).execute().body();
            int startIndex = body.indexOf(str);
            int endIndex = body.indexOf(endChar, startIndex + str.length());
            if (endIndex != -1) {
                resStr = body.substring(startIndex + str.length(), endIndex);
            }
        } catch (Exception e) {

        }
        return resStr;
    }

    public static String find(Elements scripts, String domain, String str, char endChar) {
        String res = null;
        for (Element script : scripts) {
            String src = script.attr("src");
            if (StringUtils.contains(src, "app.")) {
                String getgudingzhi = getgudingzhi(domain + src, str, endChar);
                if (StringUtils.isNotEmpty(getgudingzhi)) {
                    res = getgudingzhi;
                    break;
                }
            }
        }
        return res;
    }


    public static String getApitoken(String gudingzhi, String token) throws Exception {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        String monthStr = month < 10 ? "0" + month : String.valueOf(month);
        String result = year + "" + monthStr + gudingzhi + token;
        return result;
    }

    public static Integer getRandom() {
        int t = 0;
        Random random = new Random();
        int loopCount = random.nextInt(10) + 1;
        for (int e = 0; e < loopCount; e++) {
            t += random.nextInt(10);
        }
        return t;
    }

    public static String aes(String data, String key, String iv) {
        try {
            String encryptedText = data;
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
            String decryptedText = new String(decryptedBytes, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(decryptedText);
            return jsonObject.getString("token");
        } catch (Exception e) {
            throw new GlobalException("AES加密失败！！！");
        }
    }

    public static String jiami(String input) {
        String format = "hex"; // 替换为你想要的输出格式，可以是"hex"或"bytes"
        String res = "";
        try {
            // 创建MD5对象实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 更新哈希数据
            md.update(input.getBytes());

            // 获取哈希结果
            byte[] digest = md.digest();

            // 将哈希结果转换为十六进制字符串或字节数组
            if (format.equalsIgnoreCase("hex")) {
                StringBuilder hexString = new StringBuilder();
                for (byte b : digest) {
                    hexString.append(String.format("%02x", b));
                }
                //System.out.println("MD5 hash in hexadecimal: " + hexString.toString());
                res = hexString.toString();
            } else if (format.equalsIgnoreCase("bytes")) {
                //System.out.println("MD5 hash in byte array: " + Arrays.toString(digest));
                res = Arrays.toString(digest);
            } else {
                //System.out.println("Invalid format specified.");
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static String jiami2(String input) {
        String res = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            byte[] digest = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b & 0xff));
            }
            res = hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static String getRealToken(String phone, String pwd) throws Exception {
        String realToken = null;
//        // 连接到目标网页
        String domain = "https://www.pxb7.com/";
        Document document = Jsoup.connect(domain + "login").get();

        // 使用CSS选择器获取指定的HTML元素
        Elements scripts = document.select("script[src]");

        // 遍历并输出所有<script>标签的内容
        String gudingzhiLogin = null;
        gudingzhiLogin = find(scripts, domain, "(new Date).getMonth()+1)+", '+');

        //System.out.println(gudingzhiLogin);
        if (StringUtils.isEmpty(gudingzhiLogin)) {
            gudingzhiLogin = "PXB7";
        } else {
            gudingzhiLogin = gudingzhiLogin.replaceAll("\"", "");
        }
        //System.out.println(gudingzhiLogin);
        String input = "";
        Integer random = getRandom();
        if (Objects.nonNull(random)) {
            input = random.toString();
        }
        String token = jiami2(input);
//        System.out.println("token:" + token);
        String res = getApitoken(gudingzhiLogin, token);
//        System.out.println("res:" + res);
        String Apitoken = jiami2(res);
//        System.out.println("Apitoken:" + Apitoken);
        String url = "https://api.pxb7.com/api/login";
        Map<String, String> params1 = new HashMap<>();
        params1.put("phone", phone);
        params1.put("pwd", pwd);
        log.info(JSONObject.toJSONString(params1));

//        "mh7w0ysMKG9EVRARFBPTVNEIAZ3zkJ0q"
        long timestamp = System.currentTimeMillis() / 1000;
        String appSecret = "198f788b9ee343209e0121bf72e8c562";
        String ranString = getRanString();
        StringBuilder sb = new StringBuilder();
        sb.append("APPSECRET=");
        sb.append(appSecret);
        sb.append("&{\"PHONE\":");
        sb.append("\"" + phone + "\"");
        sb.append(",");
        sb.append("\"PWD\":");
        sb.append("\"" + pwd + "\"");
        sb.append("}");
        sb.append("&TIMESTAMP=");
        sb.append(timestamp);
        sb.append("&RANDOMSTR=");
        sb.append(ranString);

        System.out.println(sb.toString());
        String sign = DigestUtils.md5Hex(sb.toString().toUpperCase());
        System.out.println(sign);


        String response = HttpRequest.post(url)
                .header("Accept", "application/json, text/plain, */*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("ApiToken", Apitoken)
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("LoginStatus", "false")
                .header("Origin", "https://www.pxb7.com")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-site")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like " +
                        "Gecko) Chrome / 122.0 .0 .0 Safari / 537.36 ")
                .header("randomStr", ranString)
                .header("sec-ch-ua", "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Google Chrome\";v=\"122\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .header("sign", sign)
                .header("timestamp", String.valueOf(timestamp))
                .header("token", token)
                .body(JSONObject.toJSONString(params1)).execute().body();

        log.info(response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if ("200".equals(jsonObject.getString("code"))) {
            String data = jsonObject.getString("data");
            String key = null;
            String iv = null;
            try {
                String getstr = find(scripts, domain, "\"api/login\"===", ';');
                String str = ")(";
                String resStr = "";
                int startIndex = getstr.indexOf(str);
                int endIndex = getstr.indexOf(")", startIndex + str.length());
                if (endIndex != -1) {
                    resStr = getstr.substring(startIndex + str.length(), endIndex);
                }
                if (resStr.contains(",")) {
                    String[] split = resStr.split(",");
                    if (split.length == 3) {
                        key = split[1].replaceAll("\"", "");
                        iv = split[2].replaceAll("\"", "");
                    }
                }
            } catch (Exception e) {

            }
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(iv)) {
                key = "C01F8012D3F6386C";
                iv = "245C3EA487E944FD";
            }
            realToken = aes(data, key, iv);
            //System.out.println(realToken);
        }
        return realToken;
    }

    /**
     * 获取随机数
     *
     * @return
     */
    public static String getRanString() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 9; i++) {
            str += random.nextInt(9);
        }
        if (str.startsWith("0")) {
            str = str.replaceFirst("0", "1");
        }
        return str;
    }

    //    public static String gettoken() throws Exception {
//        String s = "pxb7pcwebsadfjlk"; // 密钥
//        String t = "sadfjlkpxb7pcweb"; // 初始化向量
//        String e = getRandom().toString(); // 明文
//
//        // 将密钥和初始化向量转换为字节数组
//        byte[] keyBytes = s.getBytes(StandardCharsets.UTF_8);
//        byte[] ivBytes = t.getBytes(StandardCharsets.UTF_8);
//
//        // 创建密钥规范和初始化向量规范
//        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
//        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
//
//        // 创建加密器并初始化
//        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
//
//        // 加密明文
//        byte[] plaintextBytes = e.getBytes(StandardCharsets.UTF_8);
//        byte[] encryptedBytes = cipher.doFinal(plaintextBytes);
//
//        // 将加密后的字节数组转换为Base64编码的字符串
//        String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedBytes);
//        //System.out.println("Encrypted text: " + encryptedBase64);
//        //System.out.println(DigestUtils.md5Hex(encryptedBase64));
//        return DigestUtils.md5Hex(encryptedBase64);
//    }
}
